'use strict';

/**
 * Dist configuration. Used to build the
 * final output when running npm run dist.
 */
const webpack = require('webpack');
const WebpackBaseConfig = require('./Base');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const CSSSplitWebpackPlugin = require("fast-css-split-webpack-plugin");
const HappyPack = require('happypack');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
// const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

class WebpackDistConfig extends WebpackBaseConfig {

  constructor() {
    super();
    this.config = {
      mode: "production",
      cache: false,
      devtool: false,
      devServer: {
        contentBase: './src/',
        publicPath: '/assets/',
        historyApiFallback: true,
        hot: false,
        inline: true,
        port: 8000,
        disableHostCheck: true,
        proxy: [{
          context: [
            '/vendor-info-service'
          ],
          target: 'http://apistage.huilianyi.com',
          secure: false,//是否接受 HTTP  HTTPs
          changeOrigin: true
        }]
      },
      optimization: {
        minimizer: [ // 禁用webpack自身的压缩，使用ParallelUglifyPlugin
          new ParallelUglifyPlugin({
            cacheDir: '.cache/',
            uglifyJS: {
              output: {
                comments: false
              },
              compress: {
                drop_console: false,
                drop_debugger: true
              },
              warnings: true
            }
          }),
          // new OptimizeCssAssetsPlugin({
          //   assetNameRegExp: /\.css$/g,
          //   cssProcessor: require('cssnano'),
          //   cssProcessorPluginOptions: {
          //     discardComments: { removeAll: true },
          //     reduceTransforms: false,
          //     autoprefixer: false,
          //     safe: true
          //   },
          //   canPrint: true
          // })
        ],
        splitChunks: {
          chunks: 'all', // initial、async和all
          minSize: 30000, // 形成一个新代码块最小的体积
          maxAsyncRequests: 5, // 按需加载时候最大的并行请求数
          maxInitialRequests: 3, // 最大初始化请求数
          automaticNameDelimiter: '~', // 打包分割符
          name: true,
          cacheGroups: {
            vendors: { // 基本框架
              name: 'vendor',
              chunks: 'all',
              test: /node_modules\//,
            }
          }
        },
      },
      entry: {
        app: ['@babel/polyfill', './client.js'],
        vendor: [
          'react', 'react-router', 'react-dom', 'immutable', 'redux', 'braft-editor', 'qrcode.react',
          'antd', 'draft-js', 'whatwg-fetch', 'html2canvas', 'parallax-js'
        ]
      },
      plugins: [
        new HappyPack({
          id: 'happyBabel',
          loaders: [{
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            },
          }],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new HappyPack({
          id: 'happyScss',
          loaders: ['css-loader', 'sass-loader', {
            loader: 'sass-resources-loader',
            options: {
              resources: path.resolve(__dirname, '../../src/styles/themes/color/default.scss'),
            }
          }],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new HappyPack({
          id: 'happyLess',
          loaders: ['css-loader', { loader: 'less-loader', options: { javascriptEnabled: true }}],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn|en|ja/),
        new webpack.optimize.AggressiveMergingPlugin(),
        new MiniCssExtractPlugin({
          filename: "[name].[hash].css"
        }),
        new CSSSplitWebpackPlugin({
          size: 4000,
          imports: true
        }),
        // new BundleAnalyzerPlugin(),
        new HtmlWebpackPlugin({
          filename: '../index.html',
          template: 'index.html',
          inject: true,
          meta: {
            mtime: `${new Date()}`
          },
          minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
            // more options:
            // https://github.com/kangax/html-minifier#options-quick-reference
          },
        }),


        new CompressionPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: /\.js$|\.css$/,
          threshold: 10240,
          minRatio: 0.8,
          // deleteOriginalAssets: true
        })
      ],
      stats: 'errors-only'
    };
  }

  /**
   * Get the environment name
   * @return {String} The current environment
   */
  get env() {
    return 'dist';
  }

  get extraCss() {
    return true
  }
}

module.exports = WebpackDistConfig;

